

package com.hmall.search.service.Impl;

import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;


    /**
     * 基础搜索
     *
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> qureyItems(RequestParams params) {
        try {
            //1.创建请求语义,指定索引库名称
            SearchRequest request = new SearchRequest("item");
            //2.设置查询类型:构建查询类型
            buildBasicQuery(params, request);
            //设置分页参数分页
            //查询起始页数
            int page = params.getPage();
            //每页条数
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //排序
            String sortBy = params.getSortBy();
            if (sortBy != null && !sortBy.equals("")) {
                if ("sold".equals(sortBy)) {
                    request.source().sort(sortBy, SortOrder.DESC);
                } else if ("price".equals(sortBy)) {
                    request.source().sort(sortBy, SortOrder.ASC);
                }
            }

            //设置高亮字段
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            SearchHits searchHits = response.getHits();
            // 4.1.获取总条数
            long total = searchHits.getTotalHits().value;
            System.out.println("共搜索到" + total + "条数据");
            // 4.2.文档数组
            SearchHit[] hits = searchHits.getHits();
            // 4.3.遍历
            List<ItemDoc> list = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                // 获取文档source
                String json = hit.getSourceAsString();
                // 反序列化
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
                // 获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    // 根据字段名获取高亮结果
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        // 获取高亮值
                        String name = highlightField.getFragments()[0].string();
                        // 覆盖非高亮结果
                        itemDoc.setName(name);
                    }
                }
                list.add(itemDoc);
            }
            return new PageDTO<>(total, list);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void insertById(Long id) {
        try {
            //获取商品信息
            Item item = itemClient.getById(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 搜索框自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            System.out.println(prefix);
            //1.准备请求语义,指定索引库
            SearchRequest request = new SearchRequest("item");
            //2.准备DSL
            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("my_suggestion"
                            , SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(prefix)
                                    .skipDuplicates(true)
                                    .size(10)));
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析响应数据
            //4.1 获取补全结果
            CompletionSuggestion suggestions = response.getSuggest().getSuggestion("my_suggestion");
            //4.2 获取option
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //4.3 遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取过滤聚合选项
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "categoryAgg");
            result.put("category", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations, "brandAgg");
            result.put("brand", cityList);


            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 构建基础查询语义
     *
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //构建布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断key是否为空
        if (params.getKey() == null || "".equals(params.getKey())) {
            //如果key为空,使用matchall查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            //key不为空,选择match精准查询
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        //分类条件搜索
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        //品牌条件搜索
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        //价格条件搜索
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }

        //将查询类型条件封装
        request.source().query(boolQueryBuilder);
    }


    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(30)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(30)
        );
    }


    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

}
